//
//  SLHomePageVC.m
//  SlockApp
//
//  Created by 凯朱 on 2024/7/10.
//

#import "SLHomePageVC.h"
#import "SLHomeDeviceCell.h"
#import "SLHomeMenuView.h"
#import "SLAddDeviceVC.h"
#import "SLUnlockAlertView.h"
#import "SLPreferencesSetVC.h"
#import "SLLockDetailVC.h"
#import "SLCreateAccessVC.h"
#import "SLLockLogVC.h"
#import "SLAccessManagerVC.h"
#import "SLDeviceSettingVC.h"
#import "SLWorkInSelectVC.h"
#import "SEGImagePickerManager.h"
#import "SLPrivateVC.h"
#import "SLHomeGuestCell.h"
#import "SLIbeaconManager.h"
#import "SLAboutUsVC.h"
#import "SLHomeDefaultView.h"
#import "SLDeveloperVC.h"
#import "SLChangePswdVC.h"
#import "SLHomeBridgeCell.h"
#import "SLBridgeDetailVC.h"
#import "SocketRocketUtility.h"


static  NSString *const kCellId = @"SLHomeDeviceCell";
static  NSString *const kBridgeCellId = @"SLHomeBridgeCell";
static  NSString *const kGuestCellId = @"SLHomeGuestCell";

@interface SLHomePageVC ()<UITableViewDelegate,UITableViewDataSource,SEGImagePickerManagerDelegate,RootNavigationControllerDelegate>{
    UIButton *_refreshBtn;
    BOOL _isRefresh;
    BOOL _isDidOpenMqtt;
    
}
@property (nonatomic, strong)SLHomeMenuView *menuView;
@property (nonatomic, strong)NSMutableArray *dataArray;
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)UIButton *addBtn;
@property (nonatomic, strong)SEGImagePickerManager *imagePickerVc;
@property (nonatomic, assign)BOOL isFirstLoad;
@property (nonatomic, assign)NSInteger sysncCount;
@property (nonatomic, strong)SLLockModel *updateModel;
@property (nonatomic, strong)SLHomeDefaultView *guideView;
@end

@implementation SLHomePageVC
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (_menuView.hidden == NO) {
        [kAppWindow bringSubviewToFront:_menuView];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _isFirstLoad = YES;
   
    NSArray *logList = [[NSUserDefaults standardUserDefaults] objectForKey:@"logList"];
    if (logList) {
        NSLog(@"%@",logList);
    }
    [self addObserver];
    [self loadData:YES];
    [self setUpSubViews];
    [self loadUserData];
    RootNavigationController *nav = (RootNavigationController *)self.navigationController;
    nav.navDelegate = self;
    
    // 添加向右滑动手势识别器
    UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeRight:)];
    swipeRight.direction = UISwipeGestureRecognizerDirectionRight; // 设置方向为向右
    [self.view addGestureRecognizer:swipeRight];
    [self connectCameraScoket];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    if ([self isTableViewContentSmallerThanFrame]) {
        NSLog(@"TableView内容不足一屏");
        self.addBtn.hidden = NO;
    } else {
        self.addBtn.hidden = YES;
    }
}

- (BOOL)isTableViewContentSmallerThanFrame {
    CGFloat totalHeight = 0;
    
    // 计算所有section的高度
    NSInteger sectionCount = [self numberOfSectionsInTableView:self.tableView];
    for (NSInteger section = 0; section < sectionCount; section++) {
        // 添加section header高度
        totalHeight += [self tableView:self.tableView heightForHeaderInSection:section];
        
        // 计算所有row的高度
        NSInteger rowCount = [self tableView:self.tableView numberOfRowsInSection:section];
        for (NSInteger row = 0; row < rowCount; row++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
            totalHeight += [self tableView:self.tableView heightForRowAtIndexPath:indexPath];
        }
        
        // 添加section footer高度
        totalHeight += [self tableView:self.tableView heightForFooterInSection:section];
    }
    
    return totalHeight < self.tableView.frame.size.height;
}

-(void)connectCameraScoket{
    [[SocketRocketUtility instance] SRWebSocketOpenWithURLString:WSS_main];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(srWebSocketDidOpen) name:kWebSocketDidOpenNote object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(srWebSocketDidReceiveCloseMsg:) name:kWebSocketDidCloseNote object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(srWebSocketDidReceiveMsg:) name:kWebSocketdidReceiveMessageNote object:nil];
}

-(void)srWebSocketDidOpen{
    NSLog(@"websocket开启成功");
    //在成功后需要做的操作。。。
    //登录
    NSDictionary *params = @{@"token":kToken};
    [[SocketRocketUtility instance] sendAction:@"login" params:params];
}

//连接断开
-(void)srWebSocketDidReceiveCloseMsg:(NSNotification *)note{
    //收到服务端发送过来的消息
    NSString * message = note.object;
    NSLog(@"websocket关闭：%@",message);
}

-(void)srWebSocketDidReceiveMsg:(NSNotification *)note{
    //收到服务端发送过来的消息
    NSString *message = note.object;
    NSDictionary *result = [ZCTool dictionaryWithJsonStr:message];
    NSString *action = result[@"action"];
    NSLog(@"******* socket收到数据了：message:\n%@ ******* ",message);
    if ([action isEqualToString:@"refreshDeviceList"]) {
        [self loadData:NO];
    }
}

// 手势处理方法
- (void)handleSwipeRight:(UISwipeGestureRecognizer *)gesture {
    [self showMenuAction];
}

-(void)rootNavigationControllerHandleNavigationTransition:(UIScreenEdgePanGestureRecognizer *)recognizer{
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        [self showMenuAction];
    }
}

-(void)addObserver{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshList:) name:@"kRefreshDeviceList" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bridgeBecomeOnline:) name:@"kBridgeBecomeOnline" object:nil];
    
}

-(void)refreshList:(NSNotification *)notify{
    SLLockModel *oneModel = notify.object[@"model"];
    if (oneModel) {
        [self updateOneModel:oneModel];
    }else{
        [self loadData:NO];
    }
}

-(void)bridgeBecomeOnline:(NSNotification *)notify{
    dispatch_main_async_safe(^{
        NSString *deviceNo = notify.object[@"deviceNo"];
        [self->_dataArray enumerateObjectsUsingBlock:^(SLLockModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.deviceNo isEqualToString:deviceNo]) {
                NSLog(@"网关%@上线了",deviceNo);
                [self reloadAndSysncBridgeOnlineStatus:obj onlineStatus:@"1"];
                *stop = YES;
            }
        }];
    });
}

-(void)loadUserData{
    [ZKHttpManager getWithPath:@"/msl_user/getUserInfo" params:nil finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
        if (isSuccessed){
            [[UserManager sharedUserManager] saveUserInfo:result[@"result"]];
        }
        [self.menuView refreshSubViews];
    }];
}

-(void)loadData:(BOOL)showLoading{
    if (![ZCTool checkNetWork]) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self->_isRefresh = NO;
            [self->_refreshBtn.imageView.layer removeAllAnimations];
        });
        _dataArray = [[NSMutableArray alloc] initWithArray:[UserManager getUserDeviceList]];
        [self refreshSubViews];
        return;
    }
    kWeakSelf(self);
    NSDictionary *params = @{@"page":@(1),
                             @"pageSize":@(99)};
    if (showLoading)  [ZCTool showLoadingOnKeyWindow];
    [ZKHttpManager getWithPath:@"/msl_user/BindDeviceList" params:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
        [ZCTool hideLoadingOnKeyWindow];
        self->_isRefresh = NO;
        [self->_refreshBtn.imageView.layer removeAllAnimations];
        if (weakself.updateModel) {
            weakself.updateModel.isUpdating = NO;
            weakself.updateModel = nil;
        }
        if (weakself.isFirstLoad){
            weakself.isFirstLoad = NO;
            [weakself checkBindKey];
        }
        if (isSuccessed == NO){
            kShowToast(message);
            [weakself refreshSubViews];
            return;
        }
        
        [weakself.dataArray removeAllObjects];
        NSArray *deviceList = [[NSArray alloc] initWithArray:result[@"result"][@"deviceList"]];
        NSArray *shareList = [[NSArray alloc] initWithArray:result[@"result"][@"shareList"]];
        NSMutableArray *devices = [NSMutableArray new];
        //更新数据源
        __block BOOL isHaveBridge = NO;
        [deviceList enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL * _Nonnull stop) {
            SLLockModel *model = [SLLockModel modelWithDictionary:dict];
            [devices addObject:model];
            if ([model.deviceCategory isEqualToString:@"2"]) {
                isHaveBridge = YES;
            }
            [weakself.dataArray addObject:model];
        }];
        [shareList enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            SLLockModel *model = [SLLockModel modelWithDictionary:obj];
            model.deviceCategory = @"1";
            model.isGuest = YES;
            BOOL isUseOnTime = model.keyType == 3 && [kSTRING(model.isUse) isEqualToString:@"1"];
            if (!isUseOnTime) {
                [weakself.dataArray addObject:model];
            }
        }];
        
        [UserManager updateUserDeviceListWith:devices];
        [[SLIbeaconManager sharedManager] startUserDeviceMonitoring];
        [weakself refreshSubViews];
    }];
}


-(void)reloadAndSysncBridgeOnlineStatus:(SLLockModel *)model onlineStatus:(NSString *)onlineStatus{
    model.onlineStatus = onlineStatus;
    [self->_tableView reloadRowAtIndexPath:model.indexPath withRowAnimation:UITableViewRowAnimationNone];
    [ZKHttpManager sysncDeviceDataWith:@{@"deviceNo":model.deviceNo,@"deviceId":model.deviceId,@"onlineStatus":onlineStatus} finished:nil];
}

//检测是否有分享的钥匙绑定
-(void)checkBindKey{
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    if (kSTRING(app.shareInfo[@"keyId"]).length > 0) {
        [app bindKeyWith:app.shareInfo];
    }
}

-(void)refreshSubViews{
    if (self.dataArray.count == 0) {
        NSString *firstInstall = [[NSUserDefaults standardUserDefaults] objectForKey:@"kFirstInstallFlag"];
        if (![firstInstall isEqualToString:@"1"]) {
            [self showGuideView];
        }else{
            [ZCTool showDefaultImageOnView:self.tableView];
        }
    }else{
        [ZCTool hideDefaultImageOnView:self.tableView];
    }
    [self.tableView reloadData];
    [self.view setNeedsLayout];
}

-(void)showGuideView{
    if (!_guideView) {
        _guideView = [SLHomeDefaultView viewFromXIB];
        _guideView.frame = CGRectMake(0, SafeAreaTopHeight, kScreenWidth, kScreenHeight-SafeAreaTopHeight);
    }
    kWeakSelf(self);
    [self.view addSubview:_guideView];
    [_guideView setBtnBlock:^(NSInteger btnIndex) {
        [weakself handleGuideBtnAction:btnIndex];
    }];
}

-(void)handleGuideBtnAction:(NSInteger)index{
    [self addDeviceAction];
}

-(void)refreshAction:(UIButton *)sender{
    if (_isRefresh) return;
    _isRefresh = YES;
    _refreshBtn = sender;
    [_refreshBtn.imageView rotate360Degree];
    [self loadData:NO];
}

-(void)setUpSubViews{
    self.title = kLocalString(@"Home");
    [self addNavigationItemWithImageNames:@[@"icon_nav_menu"] isLeft:YES target:self action:@selector(showMenuAction) tags:@[@"1000"]];
    [self addNavigationItemWithImageNames:@[@"icon_refresh"] isLeft:NO target:self action:@selector(refreshAction:) tags:@[@"1000"]];
    [self.view addSubview:self.tableView];
    _menuView = [SLHomeMenuView viewFromXIB];
    _menuView.frame = CGRectMake(-kScreenWidth, 0, kScreenWidth, kScreenHeight);
    kWeakSelf(self);
    [_menuView setBtnBlock:^(NSInteger btnIndex) {
        [weakself handleMenuBtnAction:btnIndex];
    }];
    [_menuView setMenuCellBlock:^(SLHomeMenuModel * _Nonnull model) {
        [weakself handleMenuCellAction:model];
    }];
    [kAppWindow addSubview:self.menuView];
  
    self.addBtn.hidden = YES;
    [self.view addSubview:self.addBtn];
}

-(void)showMenuAction{
    kWeakSelf(self);
    _menuView.hidden = NO;
    
    _menuView.mj_x = 0;
    _menuView.bgView.mj_x = - kScreenWidth/4*3;
    [UIView animateWithDuration:0.1 animations:^{
        self->_menuView.alpha = 1;
    }];
    [UIView animateWithDuration:0.25 animations:^{
        weakself.menuView.bgView.mj_x = 0;
    }];
}

-(void)hideMenuView:(BOOL)isHidden{
    if (isHidden) {
        self->_menuView.hidden = YES;
    }
    kWeakSelf(self);
    [UIView animateWithDuration:0.25 animations:^{
        weakself.menuView.bgView.mj_x = - kScreenWidth/4*3;
        self.menuView.alpha = 0;
    } completion:^(BOOL finished) {
        self->_menuView.hidden = YES;
    }];
}

-(void)addDeviceAction{
    if (_guideView) {
        [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"kFirstInstallFlag"];
        [_guideView removeFromSuperview];
        [self refreshSubViews];
    }
    SLAddDeviceVC *vc = [[SLAddDeviceVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark -
#pragma mark - ================<侧滑菜单按钮事件>===============
-(void)handleMenuCellAction:(SLHomeMenuModel *)model{
    NSString *title = model.title;
    if ([title isEqualToString:kLocalString(@"Sign out")]){
        [SLTipAlertView showWith:kLocalString(@"Are you sure you want to Log Out?") content1:@"" content2:@"" doneBtn:kLocalString(@"Log out") cancelBtn:kLocalString(@"Cancel") action:^(NSInteger index) {
            if (index == 1) {
                [[UserManager sharedUserManager] clearUserInfo];
                [[SLBluetoothManager sharedManager] disConnectPeripheral];
                KPostNotification(KNotificationLoginStateChange, @NO);
                
            }
        }];
        return;
    }
    
    [self hideMenuView:YES];
    RootViewController *vc = nil;
    RootWebViewController *webVc = nil;
    if ([title isEqualToString:kLocalString(@"Preferences")]) {
        vc = [[SLPreferencesSetVC alloc] init];
    }else if ([title isEqualToString:kLocalString(@"Works with")]){
        vc = [[SLWorkInSelectVC alloc] init];
    }else if ([title isEqualToString:kLocalString(@"Change password")]){
        vc = [[SLChangePswdVC alloc] init];
    }else if ([title isEqualToString:kLocalString(@"Terms & conditions")]){
        vc = [[SLAboutUsVC alloc] init];
    }else if ([title isEqualToString:kLocalString(@"Buy a new lock")]){
        webVc = [[RootWebViewController alloc] initWithUrl:@"https://www.baidu.com"];
    }else if ([title isEqualToString:kLocalString(@"Contact us")]){
        NSURL *url = [NSURL URLWithString:@"https://www.ai2safety.com/blog"];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
        }
    }else if ([title isEqualToString:kLocalString(@"Add new device")]){
        [self addDeviceAction];
    }
    
    
    if (vc) {
        vc.title = title;
        [self.navigationController pushViewController:vc animated:YES];
    }else if(webVc){
        [self.navigationController pushViewController:webVc animated:YES];
    }
}

-(void)handleMenuBtnAction:(NSInteger)index{
    if (index == 1) {//编辑名字
        [self showInputView];
    }else if (index == 2){//修改头像
        [self pushPhotoVc];
    }else if (index == 3){//soupport
        NSURL *url = [NSURL URLWithString:@"https://www.ai2safety.com/support"];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
        }
//        NSString *url = [NSString stringWithFormat:@"%@/index.html#/appsupport/index",URL_web];
//        RootWebViewController *webVc = [[RootWebViewController alloc] initWithUrl:url];
//        webVc.title = kLocalString(@"Support");
//        [self.navigationController pushViewController:webVc animated:YES];
    }else if (index == 4){//分享
        
    }
    else if (index == 99){//关闭菜单
        [self hideMenuView:NO];
    }
    else if (index == 100){//开发者模式
        [self hideMenuView:YES];
        SLDeveloperVC *vc = [[SLDeveloperVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

-(void)pushPhotoVc{
    self.imagePickerVc = [[SEGImagePickerManager alloc] init];
    self.imagePickerVc.themeColor = KColor_Y;
    self.imagePickerVc.delegate = self;
    self.imagePickerVc.sourceType = SEGImagePickerManagerSourceTypePhotoLibrary;
    self.imagePickerVc.allowPreview = NO;
    self.imagePickerVc.maxImagesCount = 1;
    [self.imagePickerVc presentImagePickerControllerWithAnimated:YES completion:nil superVC:self];
}

-(void)seg_imagePickerManager:(SEGImagePickerManager *)manager didFinishPickingPhotos:(NSArray<UIImage *> *)photos assets:(NSArray<PHAsset *> *)assets isSelectOriginalPhoto:(BOOL)isSelect{
    if (photos.count == 0) {
        return;
    }
    [ZCTool showLoadingOnKeyWindow];
    NSData *data = [photos[0] scaleWithFileBytes:100];
    [ZKHttpManager uploadFilesWithParams:data finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
        if (!isSuccessed) {
            [ZCTool hideHudOnKeyWindow];
            kShowToast(message);
            return;
        }
        NSString *url = result[@"result"][@"address"];
        [self updateUserInfo:url headImage:photos[0] name:@""];
    }];
}

-(void)showInputView{
    __weak SLInputAlertView *alert = [SLInputAlertView viewFromXIB];
    alert.titleLbl.text = kLocalString(@"Edit Name");
    [alert setBtnBlock:^(NSString *text, NSInteger btnIndex) {
        if (btnIndex == 1) {
            if (text.length == 0) {
                kShowToast(@"Enter your name");
                return;
            }
            [alert removeFromSuperview];
            [ZCTool showLoadingOnKeyWindow];
            [self updateUserInfo:nil headImage:nil name:text];
        }else{
            [alert removeFromSuperview];
        }
    }];
    [kAppWindow addSubview:alert];
}

-(void)updateUserInfo:(NSString *)headUrl headImage:(UIImage *)headImage name:(NSString *)name{
    kWeakSelf(self);
    NSDictionary *params;
    if (name.length > 0) {
        NSString *userId = kSTRING(kUserInfo.userId);
        params = @{@"userId":userId,
                   @"nickName":name};
    }else{//修改头像
        params = @{@"userId":kSTRING(kUserInfo.userId),
                   @"userPicture":headUrl};
    }
    [ZKHttpManager postWithPath:@"/msl_user/update" params:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
        [ZCTool hideLoadingOnKeyWindow];
        if (!isSuccessed) {
            kShowToast(message);
            return;
        }
        if (name.length > 0) {
            weakself.menuView.nameLbl.text = name;
        }else{
            [weakself.menuView.nameBtn setImageWithURL:[NSURL URLWithString:headUrl] forState:UIControlStateNormal placeholder:headImage];
        }
    }];
}

-(void)handleBridgeAction:(NSInteger)index model:(SLLockModel *)model cell:(id)cell{
    kCurClickDevice = model;
    kWeakSelf(self);
    NSLog(@"点击的设备 %@",model.deviceNo);
    if (index == 1) {//详情
        [self pushToBridgeDetailVc:model];
    }else if (index == 2){//刷新
      
    }
}

-(void)handleLockAction:(NSInteger)index model:(SLLockModel *)model cell:(id)cell{
    kCurClickDevice = model;
    kWeakSelf(self);
    NSLog(@"点击的设备 %@",model.deviceNo);
    if (index == 1) {//开锁
        if (model.bridgeDeviceNo.length > 0) {
            //先尝试远程开锁
            [ZCTool showLoadingOnKeyWindowWith:kLocalString(@"Opening...")];
            [ZCTool remoteOpenLockAction:^(BOOL isSuccess, NSString * _Nonnull message) {
                if (isSuccess) {
                    [ZCTool hideLoadingOnKeyWindow];
                    [weakself openLockSuccess:cell model:model];
                    return;
                }
                //失败了尝试蓝牙开锁
                [ZCTool connectDeviceBackgroundWith:model finish:^(BOOL isSuccess) {
                    if (!isSuccess) {
                        [ZCTool hideLoadingOnKeyWindow];
                        kShowToast(message);
                        return;
                    }
                    //连接成功，去开锁
                    [ZCTool sendOpenLockSegment:^(BOOL isSuccess ,NSString *message) {
                        [ZCTool hideLoadingOnKeyWindow];
                        if (!isSuccess) {
                            kShowToast(message);
                            return;
                        }
                        [weakself openLockSuccess:cell model:model];
                    }];
                }];
                    
            }];
            return;
        }
        //2.非网关锁，蓝牙开锁
        [ZCTool openLockAction:^(BOOL isSuccess ,NSString *message) {
            if (isSuccess) {
                [weakself openLockSuccess:cell model:model];
            }else{
                kShowToast(message);
            }
        }];
    }else if (index == 2){//创建钥匙
        SLAccessManagerVC *vc = [[SLAccessManagerVC alloc] init];
        vc.model = model;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (index == 3){//查看日志
        SLLockLogVC *vc = [[SLLockLogVC alloc] init];
        vc.model = model;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (index == 4){//刷新
        if (_updateModel) {
            kShowToast(@"The device is updating...");
            return;
        }
        //同步开锁日志和钥匙数据
        [ZCTool connectDeviceWith:model toast:kLocalString(@"Connecting...") finish:^(BOOL isSuccess) {
            if (isSuccess) {
                [self sysncDeviceData:model];
            }
        }];
    }else if (index == 5){//设置
        SLDeviceSettingVC *vc = [[SLDeviceSettingVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

-(void)openLockSuccess:(id)cell model:(SLLockModel *)model{
    kWeakSelf(self);
    SLHomeDeviceCell *deviceCell;SLHomeGuestCell *guestCell;
    if ([cell isKindOfClass:[SLHomeDeviceCell class]]) {
        deviceCell = cell;
        [deviceCell playUlockAnimation:^{
            [weakself updateOneModel:model];
        }];
    }else if([cell isKindOfClass:[SLHomeGuestCell class]]){
        guestCell = cell;
        [guestCell playUlockAnimation:^{
            [weakself loadData:NO];
        }];
    }
}

-(void)updateOneModel:(SLLockModel *)oneModel{
    kWeakSelf(self);
    NSDictionary *params = @{@"page":@(1),
                             @"pageSize":@(99)};
    [ZKHttpManager getWithPath:@"/msl_user/BindDeviceList" params:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
        if (isSuccessed == NO){
            return;
        }
        NSArray *deviceList = [[NSArray alloc] initWithArray:result[@"result"][@"deviceList"]];
        //更新数据源
        __block NSInteger index = -1;
        __block SLLockModel *tempModel = nil;
        [deviceList enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL * _Nonnull stop) {
            SLLockModel *model = [SLLockModel modelWithDictionary:dict];
            if ([model.deviceNo isEqualToString:oneModel.deviceNo]) {
                index = idx;
                tempModel = model;
                *stop = YES;
            }
        }];
        if (index >= 0) {
            [weakself.dataArray replaceObjectAtIndex:index withObject:tempModel];
        }
        if (oneModel.indexPath) {
            [weakself.tableView reloadRowAtIndexPath:oneModel.indexPath withRowAnimation:UITableViewRowAnimationNone];
        }else{
            [weakself.tableView reloadData];
        }
        
    }];
}

-(void)sysncDeviceData:(SLLockModel *)model{
    
    _updateModel = model;
    _updateModel.isUpdating = YES;
    [_tableView reloadData];
    kWeakSelf(self);
    _sysncCount = 0;
    [ZCTool batchSyncDeviceKeyDatas:^(BOOL isSuccess, NSString * _Nonnull message) {
        [weakself hanldeSyncFinish];
    }];
    
    [ZCTool batchSyncDeviceOpenLogDatas:^(BOOL isSuccess, NSString * _Nonnull message) {
        [weakself hanldeSyncFinish];
    }];
    
    [[SLBluetoothManager sharedManager] getDeviceStatusInfo:^(id data) {
        NSDictionary *params = @{@"deviceElectricQty":data[@"batteryLevel"]};
        [ZKHttpManager sysncDeviceDataWith:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
            [weakself hanldeSyncFinish];
        }];
    }];
}

-(void)hanldeSyncFinish{
    self.sysncCount ++;
    if (self.sysncCount == 3){
        [ZKHttpManager sysncDeviceDataWith:@{@"syncTime":[[NSDate date] timestamp]} finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
            [self loadData:NO];
        }];
    }
}

#pragma mark - ================<tableViewDataSource>===============
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    __weak SLHomeDeviceCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellId];
    __weak SLHomeGuestCell *gusetCell = [tableView dequeueReusableCellWithIdentifier:kGuestCellId];
    __weak SLHomeBridgeCell *bridgeCell = [tableView dequeueReusableCellWithIdentifier:kBridgeCellId];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    gusetCell.selectionStyle = UITableViewCellSelectionStyleNone;
    bridgeCell.selectionStyle = UITableViewCellSelectionStyleNone;
    SLLockModel *model = _dataArray[indexPath.section];
    model.indexPath = indexPath;
    kWeakSelf(self);
    if ([model.deviceCategory isEqualToString:@"2"]) {
        bridgeCell.model = model;
        [bridgeCell setBtnBlock:^(NSInteger btnIndex, SLLockModel * _Nonnull model) {
            [weakself handleBridgeAction:btnIndex model:model cell:bridgeCell];
        }];
        return bridgeCell;
    }
    if (model.isGuest) {
        gusetCell.model = model;
        [gusetCell setBtnBlock:^(NSInteger btnIndex, SLLockModel * _Nonnull model) {
            [weakself handleLockAction:btnIndex model:model cell:gusetCell];
        }];
        return gusetCell;
    }else{
        cell.model = model;
        [cell setBtnBlock:^(NSInteger btnIndex, SLLockModel * _Nonnull model) {
            [weakself handleLockAction:btnIndex model:model cell:cell];
        }];
        [cell setCellClickBlock:^(SLLockModel * _Nonnull model) {
//            kCurClickDevice = model;
//            [weakself pushToLockDetailVc:model];
            
            if (kCurDevice && ![model.deviceNo isEqualToString:kCurDevice.deviceNo]) {
                [[SLBluetoothManager sharedManager] disConnectPeripheral];
            }
            kCurClickDevice = model;
            if ([model.deviceCategory isEqualToString:@"1"]) {
                [weakself pushToLockDetailVc:model];
            } else {
                [weakself pushToBridgeDetailVc:model];
            }
        }];
        return cell;
    }
}

#pragma mark - ================<UITableViewDelegate>===============
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    SLLockModel *model = _dataArray[indexPath.section];
    if ([model.deviceCategory isEqualToString:@"2"]) {
        return 150;
    }
    if (model.isGuest) {
        return 156;
    }
    return 230;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UITableViewHeaderFooterView *headview = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"head"];
    if (!headview) {
        headview = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"head"];
        headview.frame = CGRectMake(0, 0, kScreenWidth, 40);
        headview.contentView.backgroundColor = KClearColor;
    }
    return headview;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UITableViewHeaderFooterView *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"foot"];
    if (!footerView) {
        footerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"foot"];
        footerView.frame = CGRectMake(0, 0, kScreenWidth, 0.1);
        footerView.contentView.backgroundColor = KClearColor;
    }
    return footerView;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    SLLockModel *model = _dataArray[indexPath.section];
    if (kCurDevice && ![model.deviceNo isEqualToString:kCurDevice.deviceNo]) {
        [[SLBluetoothManager sharedManager] disConnectPeripheral];
    }
    kCurClickDevice = model;
    if ([model.deviceCategory isEqualToString:@"1"]) {
        [self pushToLockDetailVc:model];
    }else{
        [self pushToBridgeDetailVc:model];
    }
}

//- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
//    NSInteger lastSectionIndex = tableView.numberOfSections - 1;
//    NSInteger lastRowIndex = [tableView numberOfRowsInSection:lastSectionIndex] - 1;
//    
//    // 判断是否显示最后一行
//    if (indexPath.section == lastSectionIndex && indexPath.row == lastRowIndex) {
//        self.addBtn.hidden = NO;
//    } else {
//        self.addBtn.hidden = YES;
//    }
//}


#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    // 计算表格是否滚动到底部
    CGFloat contentOffsetY = scrollView.contentOffset.y;
    CGFloat contentHeight = scrollView.contentSize.height;
    CGFloat scrollViewHeight = scrollView.frame.size.height;
    
    // 当滚动到距离底部50点以内时触发
    if (contentOffsetY > contentHeight - scrollViewHeight - 20) {
        self.addBtn.hidden = NO;
    } else {
        self.addBtn.hidden = YES;
    }
}



-(void)pushToLockDetailVc:(SLLockModel *)model{
    SLLockDetailVC *vc = [[SLLockDetailVC alloc] init];
    vc.model = model;
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)pushToBridgeDetailVc:(SLLockModel *)model{
    SLBridgeDetailVC *vc = [[SLBridgeDetailVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - ================<懒加载>===============
-(UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight, kScreenWidth, kScreenHeight-SafeAreaTopHeight) style:UITableViewStyleGrouped];
        _tableView.estimatedRowHeight = 230;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerNib:[UINib nibWithNibName:kCellId bundle:nil] forCellReuseIdentifier:kCellId];
        [_tableView registerNib:[UINib nibWithNibName:kBridgeCellId bundle:nil] forCellReuseIdentifier:kBridgeCellId];
        [_tableView registerNib:[UINib nibWithNibName:kGuestCellId bundle:nil] forCellReuseIdentifier:kGuestCellId];
        _tableView.backgroundColor = KClearColor;
    }
    return _tableView;
}

- (UIButton *)addBtn {
    if (_addBtn == nil) {
        _addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _addBtn.frame = CGRectMake((self.view.width-107)/2, self.view.height-100, 107, 107);
        [_addBtn addTarget:self action:@selector(addDeviceAction) forControlEvents:UIControlEventTouchUpInside];
        [_addBtn setImage:[UIImage imageNamed:@"icon_add_home"] forState:UIControlStateNormal];
    }
    return _addBtn;
}

-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}


@end
